package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter("/*") //  拦截路径 访问所有资源都会被拦截
public class LoginFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("过滤器执行...");

        //1.获取当前访问的资源路径
        String url = request.getRequestURI();

        //判断访问资源路径是否和登录注册相关
        //2,在数组中存储登陆和注册相关的资源路径
        String[] urls = {"/employee/login",
                "/employee/logout",
                "/backend",
                "/front",
                "/user/sendMsg",
                "/user/login",

                //设置Swagger及Knife4j相关的静态资源直接放行
                "/doc.html",
                "/webjars",
                "/swagger-resources",
                "/v2/api-docs"};

        //3,遍历数组，获取到每一个需要放行的资源路径
        for (String u : urls) {

            //4,判断当前访问的资源路径字符串是否包含要放行的的资源路径字符串
            /*
                比如当前访问的资源路径是  /brand-demo/login.jsp
                而字符串 /brand-demo/login.jsp 包含了  字符串 /login.jsp ，所以这个字符串就需要放行
            */
            if (url.contains(u)) {
                log.info("可以放行的路径:{}", url);

                //找到了，放行
                filterChain.doFilter(request, response);
                //break;
                return;
            }
            log.info("不可以放行的路径:{}", url);
        }
        //判断用户是否登录
        HttpSession session = request.getSession();
        Object employee = session.getAttribute("employee");
        if (employee != null) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //4-2、判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }
//不放行的资源访问,告知浏览器当前用户没有访问权限
        String resultJson = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(resultJson);
    }
}
